
import os

class FileItem:
    
    count = 0
    
    __id = None
    __filename = None
    __extension = None
    __path = None
    
    def __init__(self, path):
        FileItem.count += 1
        self.__id = FileItem.count
        self.UpdateByPath(path)
    
    def SetFilename(self, filename):
        self.__filename = filename
        
    def UpdateByPath(self, path):
        self.__path = path
        self.__filename = os.path.basename(path)
        self.__extension = os.path.splitext(self.__filename)[-1]
        if self.__extension == '':
            self.__extension = None
        else:
            self.__extension = self.__extension[1:]
        
    
    def GetId(self):
        return self.__id
    
    def GetExtention(self):
        return self.__extension
    
    def GetPath(self):
        return self.__path
    
    def GetFilename(self):
        return self.__filename
    
    def __str__(self):
        return self.__filename

NEW_FILES_EVENT = 100
class MediaSmoolApp:
    
    def __init__(self, imgDir):
        self.__imgDir = imgDir
        self.__files = {}
        self.__viewers = []
    
    def getDir(self):
        return self.__imgDir
    
    def loadFiles(self,path):
        if not os.path.isdir(path):
            raise Exception(os.path.basename(path) + " is not a directory")
        self.__imgDir = path
        self.__files = {}
        for f in os.listdir(path):
            pfile = os.path.sep.join([path,f])
            if os.path.isfile(pfile):
                fi = FileItem(pfile)
                self.__files[fi.GetId()] = fi
        return self.__files.values()
            
    def rename(self, name, id, renameInLowercase, prefix = ""):
        name = name.strip()
        words = name.split(' ')
        name = prefix
        for word in words:
            name += word.capitalize()
        fileItem = self.__files[id]
        pfile = fileItem.GetPath()
        if renameInLowercase:
            ext = fileItem.GetExtention().lower()
        else:
            ext = fileItem.GetExtention()
        filename = ".".join([name, ext])
        newPfile = os.path.sep.join([self.__imgDir, filename])
            
        if newPfile != pfile and os.path.exists(newPfile):
            raise Exception("File already exists")
        os.rename(pfile, newPfile)
        fileItem.UpdateByPath(newPfile)
        return fileItem
        